#include <SHT1x-ESP.h>

#include <ArduinoJson.h>

#include <AsyncWebSocket.h>
#include <ESPAsyncWebServer.h>

#include <SPIFFS.h>
#include <WiFi.h>

#define ESP_getChipId()   ((uint32_t)ESP.getEfuseMac())
#define MAX_CLIENTS 4
#define QUEUE_SIZE 6

#define dataPin  14
#define clockPin 13
#define ledPin 2

SHT1x sht1x(dataPin, clockPin, SHT1x::Voltage::DC_3_3v);

typedef struct {
  float value;
  char pdata[100];
} MyData;
QueueHandle_t queue;

typedef struct {
  float temp;
  float humidity;
} MyTh;
QueueHandle_t queue_th;

const char* ssid = "fengy09";
const char* password = "01234567abc";

// http
AsyncWebServer server(80);
AsyncWebSocket ws("/chat");
AsyncWebSocketClient* activeClients[MAX_CLIENTS];

// custom
char crc(String s);
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
               void *arg, uint8_t *data, size_t len);

// wifi event handler
void Wifi_connected(WiFiEvent_t event, WiFiEventInfo_t info) {
  digitalWrite(ledPin, HIGH);
}
void Wifi_disconnected(WiFiEvent_t event, WiFiEventInfo_t info) {
  digitalWrite(ledPin, LOW);
  Serial.print("WiFi lost connection. ");
  Serial.println("Reconnecting...");
  WiFi.begin(ssid, password);
}

void task_readsensor(void* parameter) {
  float value = -1;
  String buffer = "";
  String buffer2 = "";
  for (;;) {
    // 读甲醛传感器
    if (Serial2.available() > 0) {
      int data = Serial2.read();
      buffer += (char)data;
      buffer2 += String(data, HEX) + " ";
    }

    if (buffer.charAt(0) == 0xff && buffer.length() == 9) {
      // 验证crc
      char crcValue = crc(buffer);
      if (crcValue == buffer.charAt(8)) {
        value = (float)(buffer.charAt(4) * 256 + buffer.charAt(5)) / 1000.0;
        // 生产数据
        MyData data;
        data.value = value;
        buffer2.toCharArray(data.pdata, buffer2.length() + 1);
        xQueueSend(queue, &data, portMAX_DELAY);
      }
      else
        Serial.println("crc not equal");

      buffer = "";
      buffer2 = "";
    }  // if 1

    vTaskDelay(10 / portTICK_PERIOD_MS);
  } //for
}

void task_hmi(void* parameter) {
  for (;;) {
    // json
    DynamicJsonDocument  doc(100);
    doc.clear();
    doc["time"] = millis() / 1000;
    // 消费数据
    MyData data;
    BaseType_t ok = xQueueReceive(queue, &data, portMAX_DELAY);
    if (ok == pdTRUE) {
      doc["value"] = data.value;
      doc["raw"] = String(data.pdata);
    }

    MyTh th;
    ok = xQueueReceive(queue_th, &th, portMAX_DELAY);
    if (ok == pdTRUE) {
      doc["temp"] = th.temp;
      doc["humidity"] = th.humidity;
    }
    // websocket， 发送数据
    String result = "";
    serializeJson(doc, result);

    //ws.cleanupClients();
    for (int i = 0; i < MAX_CLIENTS; i++) {
      if (activeClients[i] != nullptr) {
        if (activeClients[i]->status() == WS_CONNECTED ) {
          if (!activeClients[i]->queueIsFull()){
            activeClients[i]->text(result);
            Serial.println(data.pdata);
          }
          if (activeClients[i]->queueIsFull())
            Serial.println("queue is full");
        }
        else {
          activeClients[i] = nullptr;
        }

        // if not null
      }
    }

    //
    vTaskDelay(2000 / portTICK_PERIOD_MS);
  }

}

void task_th(void* parameter) {
  float temp;
  float humidity;

  for (;;) {
    temp = sht1x.readTemperatureC();
    delayMicroseconds(100);
    humidity = sht1x.readHumidity();
    //Serial.println("temperatrue:" + String(temp) + ",humidity:" + String(humidity));

    MyTh th;
    th.temp = temp;
    th.humidity = humidity;
    xQueueSend(queue_th, &th, portMAX_DELAY);

    vTaskDelay(2000 / portTICK_PERIOD_MS);
  }
}

void setup() {
  // Initialize the slots
  for (int i = 0; i < MAX_CLIENTS; i++) activeClients[i] = nullptr;

  Serial.begin(9600);
  Serial2.begin(9600);

  // spiffs
  if (!SPIFFS.begin()) {
    Serial.println("An Error has occurred while mounting SPIFFS");
  }
  // wifi
  // wifi ap
  IPAddress ip(192, 168, 1, 1);
  IPAddress gw(192, 168, 1, 1);
  IPAddress mask(255, 255, 255, 0);
  WiFi.softAPConfig(ip, gw, mask);
  String chip_id = "ESP_" + String(ESP_getChipId());
  const char *ssid = chip_id.c_str();
  WiFi.softAP(ssid);

  // wifi client
  int count = 0;
  Serial.println("connect to wifi ...");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    count++;
    if (count > 10) break;
  }
  WiFi.onEvent(Wifi_disconnected, ARDUINO_EVENT_WIFI_STA_DISCONNECTED);
  WiFi.onEvent(Wifi_connected, ARDUINO_EVENT_WIFI_STA_GOT_IP);

  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("connected, wifi ip:" + WiFi.localIP().toString());
  }

  // http
  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send(SPIFFS, "/index.html", "text/html");
  });

  server.on("/zepto.js.gz", HTTP_GET, [](AsyncWebServerRequest * request) {
    AsyncWebServerResponse *response = request->beginResponse(SPIFFS, "/zepto.js.gz", "text/javascript");
    response->addHeader("Content-Encoding", "gzip");
    request->send(response);
  });

  server.on("/mini-nord.css.gz", HTTP_GET, [](AsyncWebServerRequest * request) {
    AsyncWebServerResponse *response = request->beginResponse(SPIFFS, "/mini-nord.css.gz", "text/css");
    response->addHeader("Content-Encoding", "gzip");
    request->send(response);
  });

  ws.onEvent(onWsEvent);
  server.addHandler(&ws);
  server.begin();

  queue = xQueueCreate(QUEUE_SIZE, sizeof(MyData));
  queue_th = xQueueCreate(QUEUE_SIZE, sizeof(MyTh));

  // task
  xTaskCreate(
    task_readsensor,
    "task_1",
    5000,
    NULL,
    1,
    NULL);
  xTaskCreate(
    task_hmi,
    "task_2",
    10000,
    NULL,
    1,
    NULL);

  xTaskCreate(

    task_th,
    "task_rh",
    5000,
    NULL,
    1,
    NULL);

  // wifi指示灯设置
  pinMode(ledPin, OUTPUT);

  // setup
}

void loop() {
  delay(100);

  // loop
}

// CRC计算
char crc(String s) {
  int sum = 0;
  for (int i = 1; i < s.length() - 1; i++)
    sum += s[i];
  int value = ~sum + 1;
  return value & 0xff;

}

void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
               void *arg, uint8_t *data, size_t len) {
  switch (type) {
    case WS_EVT_CONNECT:
      Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
      for (int i = 0; i < MAX_CLIENTS; i++)
        if (activeClients[i] == nullptr) {
          activeClients[i] = client;
          activeClients[i]->keepAlivePeriod(1);
          break;
        }
      break;
    case WS_EVT_DISCONNECT:
      Serial.printf("WebSocket client #%u disconnected\n", client->id());
      for (int i = 0; i < MAX_CLIENTS; i++)
        if (activeClients[i] == client) {
          activeClients[i] = nullptr;
          break;
        }
      break;
    case WS_EVT_DATA:
    case WS_EVT_PONG:
    case WS_EVT_ERROR:
      Serial.printf("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t*)arg), (char*)data);
      break;
  }
}
